<?php

namespace app\admin\model\userstaff;

use app\admin\loader\ModelInspection;
use app\common\library\Auth;
use fast\Random;
use think\Env;
use think\Exception;
use think\Model;


class User extends Model
{


    // 表名
    protected $name = 'user_staff';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text'
    ];


    public function getStatusList()
    {
        return ['1' => __('Status 1'), '2' => __('Status 2'), '3' => __('Status 3')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    /**
     * 修改用户信息
     */
    public function saveUser($id, $pwd, $mobile, $avatar)
    {
        try {
            $userModel = new \app\admin\model\User();
            if ($userModel->where('id', '<>', $id)->where(['mobile' => $mobile])->find()) {
                throw  new Exception('当前手机号重复');
            }

            $salt = Random::alnum();
            $userModel->where('id', $id)->update([
                'password' => Auth::instance()->getEncryptPassword($pwd, $salt),
                'pwd' => $pwd,
                'avatar' => $avatar ?? '',
                'username' => $mobile,
                'mobile' => $mobile,
                'salt' => $salt,
                'status' => 'normal',
            ]);
        } catch (Exception $e) {
            throw $e;
        }
    }




    public function doSave($param, $ids = 0) {

        $depart_id = $param['user_staff_class_id'] ?? 0;
        $staff_code = $param['staff_code'] ?? '';
        $staff_name = $param['name'] ?? '';
        $mobile = $param['mobile'] ?? '';
        $duty = $param['status'] ?? '';
//        $figure_images = $param['figure_images'] ?? '';



        if(empty($param['figure_images'])) {
            return [
                'code' => 1,
                'msg' => '请输入用户身份识别图像',
            ];
        }

        if(empty($staff_code)) {
            return [
                'code' => 1,
                'msg' => '请输入工号',
            ];
        }
        if(!$ids){      //添加时判断
            if($this->where(['staff_code' => $staff_code])->find()){
                return [
                    'code' => 1,
                    'msg' => '当前工号重复',
                ];
            }
        }else{
            if($this->where(['staff_code' => $staff_code])->where('id', '<>', $ids)->find()){
                return [
                    'code' => 1,
                    'msg' => '当前工号重复',
                ];
            }
        }


        if(empty($staff_name)) {
            return [
                'code' => 1,
                'msg' => '请输入姓名',
            ];
        }

        if(!$depart_id) {
            return [
                'code' => 1,
                'msg' => '请选择归属地区',
            ];
        }

        if(empty($duty)) {
            return [
                'code' => 1,
                'msg' => '请输入职务',
            ];
        }

        if(empty($mobile)) {
            return [
                'code' => 1,
                'msg' => '请输入手机号',
            ];
        }

        $userModel = new \app\admin\model\User();
        if(!$ids){      //添加时判断
            if($this->where(['mobile'=> $mobile])->find()){
                return [
                    'code' => 1,
                    'msg' => '当前手机号重复',
                ];
            }

            if($userModel->where(['username|mobile' => $mobile])->find()){
                return [
                    'code' => 1,
                    'msg' => '会员已绑定此手机号',
                ];
            }

            $data = [];
            $data['username'] = $mobile;
            $data['mobile'] = $mobile;
            $data['nickname'] = $staff_name;
            $salt = \fast\Random::alnum();
            $data['password'] = \app\common\library\Auth::instance()->getEncryptPassword('123456', $salt);
            $data['salt'] = $salt;
            $data['status'] = "normal";
            $data['pwd'] = "123456";
            $data['avatar'] = $param['images'];

            $flag = $userModel->save($data);
            if(false === $flag) {
                return [
                    'code' => 1,
                    'msg' => '写入用户失败'
                ];
            }
            $param['user_id'] = $userModel->id;
            $result = $this->allowField(true)->save($param);

        }else{
            if($this->where(['mobile'=> $mobile])->where('id', '<>', $ids)->find()){
                return [
                    'code' => 1,
                    'msg' => '当前手机号重复',
                ];
            }

            $objStaff = $this->where(['id' => $ids])->find();
            if(!$objStaff){
                return [
                    'code' => 1,
                    'msg' => '当前员工不存在',
                ];
            }

            if($userModel->where(['username|mobile' => $mobile])->where('id', '<>', $objStaff->user_id)->find()){
                return [
                    'code' => 1,
                    'msg' => '会员已绑定此手机号',
                ];
            }

            $flag = $objStaff->save($param);
            if(false === $flag) {
                return [
                    'code' => 1,
                    'msg' => '编辑用户失败'
                ];
            }
            $objUser = $userModel->where(['id' => $objStaff->user_id ])->find();
            $result = $objUser->save([
                'username' => $mobile,
                'mobile' => $mobile,
                'nickname' => $staff_name,
            ]);
        }


        if(false === $result) {
            return [
                'code' => 1,
                'msg' => '写入员工失败'
            ];
        }

        return [
            'code' => 0,
            'msg' => 'ok'
        ];
    }


    /**
     * 人脸识别
     * @param $mobile
     */
    public function validateFigure($mobile, $image)
    {
        try {
            $user_info = $this->db()->where('mobile', $mobile)
                ->field('mobile,figure_images,user_id')
                ->find();
            if (empty($user_info)) {
                throw  new Exception('请联系管理员登记身份');
            }
            //测试地址
//            $image = base64_encode(file_get_contents('http://zhifa.cn' . '/uploads/20221119/dbf351159ab2bd71f77d6a1aeb3ed798.jpg'));

            $figure_images = explode(',', $user_info['figure_images']);
            $url = Env::get('curlPost.url');
            $result = false;
            foreach ($figure_images as $v) {
                $data = post_send($url,  json_encode(array(
                    "imageBase64A" => base64_encode(file_get_contents('http://zhifazuixin.cn' . $v)),
                    "imageBase64B" => $image,
                    "faceScoreThreshold" => 0,
                    "needFaceInfo" => true,
                )));

                $data = json_decode($data,true);
                if ($data['code'] === 0 && $data['data']['confidence'] > 70){
                    $result = true;
                    break;
                }
            }
            if ($result){
                return \app\admin\loader\Model::User()->where('id', $user_info['user_id'])->value('pwd');
            }
            return  false;
        } catch (Exception $e) {
            throw  $e;
        }
    }

}
